package com.chezhujie.www.controller;

import com.chezhujie.www.domain.CzjcommentsPic;
import com.chezhujie.www.service.CzjcommentsPicService;
import com.sys.core.page.Pagination;
import com.sys.core.utils.ConvertObj;
import com.sys.core.utils.Fileupload;
import com.sys.core.utils.UUIDUtils;
import com.sys.user.base.controller.BaseController;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *   评论图片
 * Created by 汤伟杰 on 2017/5/23.
 */
@Controller
@RequestMapping("/czjcommentspic")
public class CzjcommentsPicController extends BaseController<CzjcommentsPic> {
    @Autowired
    private CzjcommentsPicService czjcommentspicService;

    /** 列表 **/
    @RequestMapping("/list.do")
    public String list(Integer pageNo, Integer pageSize, CzjcommentsPic czjcommentspic, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(czjcommentspic,req,model);
        setCommentsId(model);
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(czjcommentspic);
            Pagination pagination = czjcommentspicService.list(pageNo.intValue(), pageSize.intValue(), params, model);
            model.addAttribute("pagination", pagination);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed","获取评论图片列表失败!"+e.getMessage());
        }
        model.addAttribute("entity", czjcommentspic);
        return "czjcommentspic/list";
    }
    /**
    * api接口评论图片列表
    * @param pageNo
    * @param pageSize
    * @param czjcomments
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiList.jn")
    public void apiList(Integer pageNo, Integer pageSize, CzjcommentsPic czjcommentspic,
        HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(czjcommentspic);
            Pagination pagination = czjcommentspicService.apilist(pageNo.intValue(), pageSize.intValue(), params, model);
            jsonResult(1,"","",pagination,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"","获取评论图片列表失败!"+e,"",resp);
        }

    }
    /**
    * api接口评论图片详情
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiDetail.jn")
    public void apiDetail(HttpServletRequest req, HttpServletResponse resp,
    ModelMap model) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<String> enumeration = req.getParameterNames();
        if(enumeration.hasMoreElements()){
            String next = enumeration.nextElement();
            params.put(next, req.getParameter(next));
        }

        try {
            Map<String,Object> result = czjcommentspicService.getApiDetail(params);
            jsonResult(1,"","",result,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"99","获取评论图片详情失败!"+e,"",resp);
        }

    }
    /** api测试页面 **/
    @RequestMapping("/apiTest.do")
    public String apiList(HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        model.addAttribute("entity",new HashMap<String,Object>());
        return "czjcommentspic/apiTest";

    }

    /** 保存 **/
    @RequestMapping("/save.do")
    public String save(CzjcommentsPic czjcommentspic,
            @RequestParam(value = "filePicPath", required = false) MultipartFile multipartFile_PicPath,
                      HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {

            if(StringUtils.isNotBlank(czjcommentspic.getCommentPicId())){
                String picPath = czjcommentspic.getPicPath();
                setPicPath(czjcommentspic,multipartFile_PicPath,req);
                czjcommentspicService.update(czjcommentspic);
                Fileupload.deleteFile(req,picPath);


            }else{
                czjcommentspic.setCommentPicId(UUIDUtils.getUUID());
                setPicPath(czjcommentspic,multipartFile_PicPath,req);
                czjcommentspicService.insert(czjcommentspic);
            }
            model.addAttribute("success", "保存评论图片成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "保存评论图片失败!详情："+e.getMessage());
        }
        return "redirect:list.do";
    }
    private void setPicPath(CzjcommentsPic czjcommentspic, MultipartFile multipartFile, HttpServletRequest req) throws Exception {
        if((!multipartFile.isEmpty())&&multipartFile.getSize()>0){
            String basePath = req.getSession().getServletContext().getRealPath("/");
            String path = basePath+"upload/czjcommentspic/"+czjcommentspic.getCommentPicId()+"-"+ System.currentTimeMillis()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            Fileupload.createDir(basePath+"upload/czjcommentspic/");

            InputStream in = multipartFile.getInputStream();
            FileOutputStream out = new FileOutputStream(path);
            try {
                IOUtils.copy(in,out);
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("上传图片失败！");
            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

            String picPath = "/"+path.replace(basePath, "");
            czjcommentspic.setPicPath(picPath);
        }
    }


    /** 详情 **/
    @RequestMapping("/detail.do")
    public String detail(@RequestParam(required = true)String commentPicId,CzjcommentsPic czjcommentspic, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(czjcommentspic,req,model);
        setCommentsId(model);
        try {
            CzjcommentsPic entity = czjcommentspicService.queryById(czjcommentspic.getCommentPicId());
            model.addAttribute("entity", entity);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "查询评论图片出错!详情："+e.getMessage());
        }
        return "czjcommentspic/detail";
    }
    /** 新增或修改 **/
    @RequestMapping("/add.do")
    public String add(CzjcommentsPic czjcommentspic, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(czjcommentspic,req,model);
        setCommentsId(model);
        if(StringUtils.isNotBlank(czjcommentspic.getCommentPicId())){
            czjcommentspic = czjcommentspicService.queryById(czjcommentspic.getCommentPicId());
            model.addAttribute("entity", czjcommentspic);
        }
        return "czjcommentspic/add";
    }
    /** 删除 **/
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(required = true)String commentPicId,CzjcommentsPic czjcommentspic, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            czjcommentspicService.deleteById(czjcommentspic.getCommentPicId());
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:list.do";
    }
    private void setCommentsId(ModelMap model) {
        Map<String,Object> param = new HashMap<String,Object>();
        List<Map<String,Object>> listCommentsId = czjcommentspicService.getListCommentsId(param);
        // map.put("name","");
        // map.put("value","");
        model.addAttribute("listCommentsId", listCommentsId);
    }
    /** 审批 **/
    @RequestMapping("/approve.do")
    public String approve(@RequestParam(required = true)String commentPicId,
                          @RequestParam(required = true)Integer approveStatus,
                          HttpServletRequest req, HttpServletResponse resp,
                          ModelMap model){

        czjcommentspicService.changeApprove(commentPicId,approveStatus);
        return "redirect:detail.do?commentPicId="+commentPicId;
    }

    private void setMsg(CzjcommentsPic czjcommentspic,HttpServletRequest req, ModelMap model) {
        model.addAttribute("failed", req.getParameter("failed"));
        model.addAttribute("success", req.getParameter("success"));
        model.addAttribute("entity", czjcommentspic);
    }
}
